from pms.common.views import PostFormula
from info.utils.mail import mail_view
from info.utils.mail.sender import create_mail, InvalidRecipient
from department.models import Department
from project.models import Project


class API(PostFormula):
    def handle(self, req):
        try:
            return self.success_respond(
                mail_view(
                    create_mail(
                        user=self.user,
                        title=req['title'],
                        content=req['content'],
                        recipients=req['recipients'],
                        department=Department.objects.get(id=req['did'])
                        if 'did' in req and req['did'] is not None else None,
                        project=Project.objects.get(id=req['pid'])
                        if 'pid' in req and req['pid'] is not None else None
                    )
                )
            )
        except InvalidRecipient as e:
            return self.failed_respond('INVALID_RECIPIENT', '用户{}({})不在部门或项目的范围内'
                                       .format(e.user.name, e.user.id))
